<template>
  <div class="admin-media-registration">
    <div class="page-header">
      <h2>媒体注册审核</h2>
    </div>

    <el-card>
      <div class="toolbar">
        <el-input
          v-model="keyword"
          placeholder="搜索媒体名称/记者"
          style="width: 240px"
          clearable
          @keyup.enter="loadList"
        />
        <el-select
          v-model="status"
          placeholder="审核状态"
          clearable
          style="width: 160px"
        >
          <el-option label="全部" value="" />
          <el-option label="待审核" value="pending" />
          <el-option label="已通过" value="approved" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>
        <el-button @click="loadList" :loading="loading">查询</el-button>
        <el-button @click="exportExcel">导出</el-button>
      </div>

      <el-table :data="list" v-loading="loading" stripe>
        <el-table-column prop="mediaName" label="媒体名称" min-width="160" />
        <el-table-column prop="mediaType" label="媒体类型" width="120" />
        <el-table-column prop="journalistName" label="记者姓名" width="160" />
        <el-table-column prop="journalistPhone" label="联系电话" width="160" />
        <el-table-column prop="journalistEmail" label="联系邮箱" width="220" />
        <el-table-column label="审核状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="提交时间" width="180" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">查看</el-button>
            <el-dropdown>
              <el-button size="small" type="primary">
                审核
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleAudit(row, 'approved')">通过</el-dropdown-item>
                  <el-dropdown-item @click="handleAudit(row, 'rejected')">拒绝</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pager">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="size"
          :total="total"
          :current-page="current"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" title="注册详情" width="720px">
      <el-descriptions v-if="currentRecord" :column="2" border>
        <el-descriptions-item label="媒体名称">{{ currentRecord.mediaName }}</el-descriptions-item>
        <el-descriptions-item label="媒体类型">{{ currentRecord.mediaType }}</el-descriptions-item>
        <el-descriptions-item label="记者姓名">{{ currentRecord.journalistName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentRecord.journalistPhone }}</el-descriptions-item>
        <el-descriptions-item label="联系邮箱">{{ currentRecord.journalistEmail }}</el-descriptions-item>
        <el-descriptions-item label="报道计划" :span="2">{{ currentRecord.coveragePlan || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">{{ getStatusText(currentRecord.status) }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ currentRecord.createdTime || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { mediaApi } from '@/api/admin'
import { useExcelExport } from '@/hooks/useExcelExport'

export default {
  name: 'AdminRegisterMedia',
  components: { ArrowDown },
  setup() {
    const loading = ref(false)
    const list = ref([])
    const total = ref(0)
    const current = ref(1)
    const size = ref(10)
    const keyword = ref('')
    const status = ref('')

    const { exportListData, mapperPresets } = useExcelExport()

    const dialogVisible = ref(false)
    const currentRecord = ref(null)

    const loadList = async () => {
      loading.value = true
      try {
        const params = { page: current.value, size: size.value }
        if (status.value) params.status = status.value
        if (keyword.value) params.keyword = keyword.value
        const res = await mediaApi.getMediaRegistrationPage(params)
        if (res && (res.code === '200' || res.code === 200)) {
          const data = res.data || {}
          list.value = data.records || []
          total.value = data.total || 0
        }
      } catch (error) {
        console.error('加载媒体注册列表失败:', error)
        ElMessage.error('加载失败')
      } finally {
        loading.value = false
      }
    }

    const viewDetail = (row) => {
      currentRecord.value = row
      dialogVisible.value = true
    }

    const handleAudit = async (row, auditStatus) => {
      try {
        const res = await mediaApi.auditMediaRegistration(row.id, auditStatus, '', 'admin')
        if (res && (res.code === '200' || res.code === 200)) {
          ElMessage.success('操作成功')
          await loadList()
        } else {
          ElMessage.error(res?.msg || '操作失败')
        }
      } catch (error) {
        console.error('审核媒体注册失败:', error)
        ElMessage.error('操作失败')
      }
    }

    const handleSizeChange = (newSize) => {
      size.value = newSize
      current.value = 1
      loadList()
    }

    const handleCurrentChange = (newCurrent) => {
      current.value = newCurrent
      loadList()
    }

    const exportExcel = async () => {
      const fetchData = async () => {
        const params = { page: 1, size: 100000 }
        if (status.value) params.status = status.value
        if (keyword.value) params.keyword = keyword.value
        const res = await mediaApi.getMediaRegistrationPage(params)
        return res.data?.records || []
      }

      const mapData = (item) => ({
        '媒体名称': mapperPresets.handleEmpty(item.mediaName),
        '媒体类型': mapperPresets.handleEmpty(item.mediaType),
        '记者姓名': mapperPresets.handleEmpty(item.journalistName),
        '记者职务': mapperPresets.handleEmpty(item.journalistPosition || item.journalistTitle),
        '联系电话': mapperPresets.handleEmpty(item.journalistPhone),
        '联系邮箱': mapperPresets.handleEmpty(item.journalistEmail),
        '报道计划': mapperPresets.handleEmpty(item.coveragePlan),
        '审核状态': getStatusText(item.status),
        '提交时间': mapperPresets.handleEmpty(item.createdTime)
      })

      const columnWidths = [
        { wch: 25 },
        { wch: 15 },
        { wch: 18 },
        { wch: 18 },
        { wch: 18 },
        { wch: 25 },
        { wch: 40 },
        { wch: 12 },
        { wch: 20 }
      ]

      await exportListData(fetchData, mapData, '媒体注册列表', columnWidths, '媒体注册列表')
    }

    const getStatusText = (value) => {
      const map = {
        pending: '待审核',
        approved: '已通过',
        rejected: '已拒绝'
      }
      return map[value] || mapperPresets.handleEmpty(value)
    }

    const getStatusTagType = (value) => {
      const map = {
        pending: 'warning',
        approved: 'success',
        rejected: 'danger'
      }
      return map[value] || 'info'
    }

    onMounted(loadList)

    return {
      loading,
      list,
      total,
      current,
      size,
      keyword,
      status,
      dialogVisible,
      currentRecord,
      loadList,
      handleSizeChange,
      handleCurrentChange,
      exportExcel,
      getStatusText,
      getStatusTagType,
      viewDetail,
      handleAudit
    }
  }
}
</script>

<style scoped>
.admin-media-registration {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
}

.pager {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>
